#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <ctime>
#include "BlockQueue.hpp"
#include "Task.hpp"
using namespace std;

void *Consumer(void *arg)
{
    // BlockQueue<int> *bq = static_cast<BlockQueue<int> *>(arg);
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task> *>(arg);
    while (true)
    {
        // int data = bq->Pop();
        // printf("消费了一个数据：%d\n", data);
        Task task = bq->Pop();

        //加工处理数据
        task.run();
        cout << "处理了一个任务：" << task.GetTask() << "处理结果："<< task.GetResult() << "thread id: "<< pthread_self() << endl;
        usleep(300000);
        // sleep(1);
    }

    return nullptr;
}

void *Producter(void *arg)
{
    int data = 0;
    string opera = "+-*/%";
    int size = opera.size();
    
    // BlockQueue<int> *bq = static_cast<BlockQueue<int> *>(arg);
    BlockQueue<Task> *bq = static_cast<BlockQueue<Task> *>(arg);

    while (true)
    {
        // bq->Push(data);
        // printf("生产了一个数据：%d\n", data++);

        //模拟获取数据
        int x = rand() % 10; //[0, 9]
        int y = rand() % 10;
        char oper = opera[rand() % size];
        Task task(x, y, oper);
        usleep(13);
        cout << "生产了一个任务:" << task.GetTask() << "thread id: " << pthread_self() << endl;
        bq->Push(task);
        usleep(300000);
        // sleep(1);
    }
    return nullptr;
}
int main()
{
    srand(time(nullptr));
    pthread_t c[3];
    pthread_t p[5];
    // BlockQueue<int> *bq = new BlockQueue<int>();
    BlockQueue<Task> *bq = new BlockQueue<Task>();
    for(int i = 0; i < 3; i++)
    {
        pthread_create(&c[i], nullptr, Consumer, (void *)bq);
    }
    for(int j = 0; j < 5; j++)
    {
        pthread_create(&p[j], nullptr, Producter, (void *)bq);
    }

    for(int i = 0; i < 3; i++)
    {
        pthread_join(c[i], nullptr);

    }
    for(int j = 0; j < 5; j++)
    {
        pthread_join(p[j], nullptr);
    }
    return 0;
}